package cn.com.dstz.admin.action;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;

import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.NumberUtils;
import cn.com.dstz.utils.PinYinUtils;

/**
 * ajax 操作Action
 * @author 叶装装
 *
 */
public class AjaxAction extends BaseAction{
	
	/**
	 * 获取拼音
	 */
	public void category_fillpinyin( ){
		
		String name = getParameterByDecode( "name" );
		String pinyin = "";
		
		if( StringUtils.isNotBlank( name )){
			pinyin = PinYinUtils.getPinYinWithOutDuoyin( name ) ;
		}
		Map< String, Object > jsonMap = new HashMap< String, Object >( );
		jsonMap.put( "value", pinyin );
		
		this.responseToJsonObject( jsonMap );
		return;
	}
	
	public void membergroup_list( ){
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "ismanager", 0 );
		
		String sql = "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid and t.ismanager=:ismanager ";
		
		List< Map< String, Object >> groupList = baseService.queryForListByAll( sql, valueMap );
		
		this.ajaxResponse( JSONArray.fromObject( groupList ) );
		
	}
	
	// ------------------------------------------------------- 
	// 改变权限路径
	public void cf( ){
		
		List< Map< String, Object >> list = baseService.queryForListByAll( "select * from dstz_function", null );
		
		for( Map< String, Object > map : list ){
			Object url = map.get( "url" );
			
			if( url != null ){
				String strUrl = url.toString( );
				
				
				if( StringUtils.isNotBlank( strUrl )){
					if( StringUtils.contains( strUrl, ".jsp" )){
						System.out.println( strUrl + "  不改变JSP---------------");
						continue;
					}
					
					strUrl = strUrl.replace( "/admin/", "" );
					int p = strUrl.indexOf( "/" );
					if( p != -1 ){
						strUrl = strUrl.substring( p, strUrl.length( ) );
					}
					String newUrl = "/admin/manager" + strUrl;
					
					int update = baseService.update( "dstz_function", DataBaseUtils.getData( new String[]{
							"url"
					}, new Object[]{
							newUrl
					} ), DataBaseUtils.getData( new String[]{
							"id"
					}, new Object[]{
							map.get( "id" )
					} ) );
					
					System.out.println( update  );
					
					
				}
				
				
			}
		}
		
	}
	
	
	public void t1( ){
		HttpServletRequest request = getRequest( );
		//System.out.println( "T1===========RequestMethod: " + request.getMethod( ) + ", " + request.getCharacterEncoding( ) );
		System.out.println( "接收参数:T1" + decode( request.getParameter( "paramStr" ) ));
		
	}
	
	public void t2( ){
		HttpServletRequest request = getRequest( );
		//System.out.println( "T3===========RequestMethod: " + request.getMethod( ) + ", " + request.getCharacterEncoding( ) );
		System.out.println( "接收参数T2:" + decode( request.getParameter( "paramStr" ) ));
	}
	
	public void t3( ){
		HttpServletRequest request = getRequest( );
		//System.out.println( "T3===========RequestMethod: " + request.getMethod( ) + ", " + request.getCharacterEncoding( ) );
		System.out.println( "接收参数:T3" + decode( request.getParameter( "paramStr" ) ));
	}
	
	// ========================================================================
	public void all( ){
		
		//dstzgg( );				表结构没改变， 不执行
		//dstzfx( );表结构没改变， 不执行
		//dstztrade( );表结构没改变， 不执行
		
		System.out.println( "==============执行复杂数据的更新开始==========================");
		
		dstzmember( );
		dstzagent( );
		dstzadmin( );
		dstzcategory( );
		
		System.out.println( "==============执行复杂数据的更新结束==========================");
	}
	
	public void dstzgg( ){
		String tableName = "dstzgg";
		beforeDelete( tableName );
		List< Map< String, Object  >>tradeList = baseService.queryForListByAll( "select * from _dstzgg", null ); 
		System.out.println( tradeList.size( ) + "--->总数据");
		for( Map< String, Object > trade : tradeList ){
			int save = baseService.save( tableName, trade );
			System.out.println( "dstzgg->" + trade.get( "id" ) + "->" + save );
		}
	}
	
	public void dstzfx( ){
		String tableName = "dstzfx";
		beforeDelete( tableName );
		List< Map< String, Object  >>tradeList = baseService.queryForListByAll( "select * from _dstzfx", null ); 
		System.out.println( tradeList.size( ) + "--->总数据");
		for( Map< String, Object > trade : tradeList ){
			
			// 处理数据中的 单引号和and
//			String content = trade.get( "content" ).toString( );
//			trade.put( "content", content );
			
			int save = baseService.save( tableName, trade );
			System.out.println( "dstzfx->" + trade.get( "id" ) + "->" + save );
		}
	}
	
	
	/**
	 * 开仓
	 * 数据查询，数据插入
	 */
	public void dstztrade( ){
		String tableName = "dstztrade";
		beforeDelete( tableName );
		List< Map< String, Object  >>tradeList = baseService.queryForListByAll( "select * from _dstztrade", null ); 
		for( Map< String, Object > trade : tradeList ){
			
			set( trade, "closeposition", 0 );
			set( trade, "profit", 0 );
			set( trade, "endtime", "" );
			set( trade, "reason", "" );
			
			
			Object status = trade.get( "status" );
			
			if( status != null ){
				
				boolean _status = NumberUtils.getBoolean( status.toString( ) );
				
				if( _status  ){
					trade.put( "status", 1 );
				}else{
					trade.put( "status", 0 );
				}
				
			}else{
				trade.put( "status", 0 );	
			}


			int save = baseService.save( tableName, trade );
			System.out.println( "执行dstztrade:" + save );
		}
		
	}
	
	/**
	 * 更新member
	 * member表新增adminid 
	 * 查询所有的member, 然后再根据aid查询出admin,
	 * 保存adminid 
	 */
	public void dstzmember( ){
		String tableName = "dstzmember";
		beforeDelete( tableName );
		
		List< Map< String, Object  >> memberList = baseService.queryForListByAll( "select * from _dstzmember", null ); // 获取用户
		
		for( Map< String, Object > member : memberList ){
//			Integer groupid = ( Integer ) member.get( "groupid" );
//			if( groupid == 0 ){
//				continue; // 忽略这些无效的数据
//			}
			
			Object status = member.get( "status" );	// 查询出来的状态是 boolean
			Object aid = member.get( "aid" );
			
			set( member, "idcard", "" );
			set( member, "expiredate", "" );
			
			set( member, "mnumber", "" );
			set( member, "mpassword", "" );
			set( member, "onumber", "" );
			set( member, "opassword", "" );
			set( member, "logged", "" );
			set( member, "zt", 0 );
			set( member, "topaid", 0 );
			
			
			Map< String, Object > admin = baseService.getData( "select * from _dstzadmin where aid=" + aid + " and status=1  limit 0, 1" );
			
			if( admin != null && !admin.isEmpty( ) ){
				member.put( "adminid", admin.get( "id" ) );
			}else{
				member.put( "adminid", 0 );
			}
			
			if( status != null ){
				
				boolean _status = NumberUtils.getBoolean( status.toString( ) );
				
				if( _status  ){
					member.put( "status", 1 );
				}else{
					member.put( "status", 0 );
				}
				
			}else{
				member.put( "status", 0 );	
			}
			
			int save = baseService.save( tableName, member );
			System.out.println( "执行dstzmember:" + save );
		}
		
	}
	
	/**
	 * 更新category
	 * 根据AID查询对应的管理员，
	 * 然后更新pinyin 和 adminid
	 */
	public void dstzcategory( ){
		String tableName = "dstzcategory";
		beforeDelete( tableName );
		
		List< Map< String, Object  >> categoryList = baseService.queryForListByAll( "select * from _dstzcategory", null ); // 获取品种
		
		for( Map< String, Object > category : categoryList ){
			Object aid = category.get( "aid" );
			Map< String, Object > admin = baseService.getData( "select * from _dstzadmin where aid=" + aid + " and status=1  limit 0, 1" );
			
			if( admin != null && !admin.isEmpty( ) ){
				category.put( "adminid", admin.get( "id" ) );
				category.put( "pinyin", PinYinUtils.getPinYinWithOutDuoyin( category.get( "name" ).toString( ) ) );
				
				int save = baseService.save( tableName, category );
				
				System.out.println( "执行dstzcategory:" + save );
			}
			
		}
	}
	
	/**
	 * 更新dstzagent ,
	 * 修改居间的topaid 为对应的管理员ID
	 */
	public void dstzagent( ){
		String tableName = "dstzagent";
		beforeDelete( tableName );
		
		List< Map< String, Object  >> agentList = baseService.queryForListByAll( "select * from _dstzagent", null ); // 获取居间
		
		for( Map< String, Object > agent : agentList ){
			
			Object id = agent.get( "id" );	//	查询出ID
			Object status = agent.get( "status" );	// 查询出来的状态是 boolean
			Object type = agent.get( "type" );
			Object grade = agent.get( "grade" );
			Object gg = agent.get( "gg" );
			if( type == null ){
				agent.put( "type", 0 );
			}
			if( grade == null ){
				agent.put( "grade", 0 );
			}
			
			if( gg == null ){
				agent.put( "gg", "" );
			}
			
			// 在 admin 表中查询出对应的管理员, 可能一个aid 对应了多个 admin, 通过观察数据会发现，status=1 的全部为最顶级的用户
			Map< String, Object > admin = baseService.getData( "select * from _dstzadmin where aid=" + id + " and status=1  limit 0, 1" );
			
			if( admin != null && !admin.isEmpty( ) ){
				
				agent.put( "topaid", admin.get( "id" ) ); // 设置topaid为当前管理员的ID
				
				if( status != null ){
					
					boolean _status = NumberUtils.getBoolean( status.toString( ) );
					
					if( _status  ){
						agent.put( "status", 1 );
					}else{
						agent.put( "status", 0 );
					}
					
				}else{
					agent.put( "status", 0 );	//	 全部更新为0，使用状态
				}
				
				
				int save = baseService.save( tableName, agent );
				
				System.out.println( "执行dstzagent" + save );
				
			}
		}
		
		// 
		
	}
	
	/**
	 * 更新dstzadmin
	 */
	public void dstzadmin( ){
		String tableName = "dstzadmin";
		beforeDelete( tableName ); // 删除admin
	//	beforeDelete( "dstzagent" );// 删除agent
	
		
		//List< String > fieldsList = baseService.descTable( tableName );	 // 得到所有的列名
		
		String sql = "select ag.id as agentid, a.id as adminid, a.aid as aid, a.status as status from _dstzgroup g, _dstzadmin a left outer join _dstzagent ag on a.aid = ag.id where a.groupid = g.id";
		
		// 查询出来的总记录和admin表是对应的。。。
		//List< Map< String, Object >> adminList = baseService.queryForListByAll( "select ag.id, a.id as adid, a.aid as aid from _dstzgroup g, _dstzadmin a left outer join _dstzagent ag on a.aid = ag.id where a.groupid = g.id ", null );
		List< Map< String, Object >> adminList = baseService.queryList( sql, 0, 1000, null, DataBaseUtils.getAlias( new String[]{
				"agentid", "adminid", "aid", "status"
		}, new Type[]{
				Hibernate.INTEGER, Hibernate.INTEGER, Hibernate.INTEGER, Hibernate.INTEGER, 
		} ) );
		
		for( Map< String, Object > admin : adminList ){
			Object adminid = admin.get( "adminid" );	// 获取管理员的ID
			Object aid = admin.get( "agentid" );						// 居间ID
			Object oldaid = admin.get( "aid" );
			Object status = admin.get( "status" );	// 原数据库当为0的时候，表示的是居间添加的管理员，即没有对应居间的
			
			Map< String, Object > insertData = baseService.getData( "select * from _dstzadmin where id=" + adminid ); // 从数据库中获取对应ID的数据

			// 居间ID为空
			if( aid == null || "0".equals( status.toString( ) )) { 
				
				insertData.put( "hasagent", 0 );	// 表示没有对应居间的
			}else{
				insertData.put( "hasagent", 1 );	// 表示是有居间的
			}
			
			insertData.put( "topaid", oldaid ); // 对应新表中的 topaid,表示的是居间的ID
			insertData.put( "aid", adminid );	//	对应新表中的 aid, 表示的是管理员的ID
			
			Object name = insertData.get( "name" );
			
			if( name == null ){
				insertData.put( "name", "" );
			}
			int save = baseService.save( tableName, insertData ); // 进行管理员表的更新
			
			System.out.println( "更新admin表==" + save );
			
		}
		
	}
	
	
	
	/**
	 * 数据替换之前，删除原来所有的数据
	 * @param tableName
	 * @return
	 */
	private int beforeDelete( String tableName ){
		return baseService.deleteBySql( tableName, null );
	}
	
	private void set( Map< String, Object > data, String key, Object value ){
		if( data.get( key ) == null ){
			data.put( key, value );
		}
	}
	
	
	private static final long serialVersionUID = 1L;
	
}
